<template>
  <div class="backup-management">
    <div class="page-header">
      <h1>数据库备份管理</h1>
      <el-button type="primary" @click="showCreateBackupDialog">
        <el-icon><Plus /></el-icon>
        创建备份
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="数据库连接">
          <el-select v-model="searchForm.connection_id" placeholder="请选择数据库连接" clearable>
            <el-option
              v-for="conn in connectionList"
              :key="conn.id"
              :label="conn.name"
              :value="conn.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备份状态">
          <el-select v-model="searchForm.status" placeholder="请选择备份状态" clearable>
            <el-option label="已完成" value="completed" />
            <el-option label="备份中" value="running" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchBackupList">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 备份列表 -->
    <el-card>
      <el-table :data="backupList" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="备份名称" />
        <el-table-column prop="connection_name" label="数据库" width="150" />
        <el-table-column prop="backup_type" label="备份类型" width="120">
          <template #default="scope">
            <el-tag :type="getBackupTypeColor(scope.row.backup_type)">
              {{ getBackupTypeText(scope.row.backup_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="file_size_mb" label="文件大小" width="120">
          <template #default="scope">
            {{ scope.row.file_size_mb }}MB
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusColor(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_by_name" label="创建者" width="120" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="downloadBackup(scope.row)"
              :disabled="scope.row.status !== 'completed'"
            >
              下载
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="restoreBackup(scope.row)"
              :disabled="scope.row.status !== 'completed'"
            >
              恢复
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="deleteBackup(scope.row)" 
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchBackupList"
          @current-change="fetchBackupList"
        />
      </div>
    </el-card>

    <!-- 创建备份对话框 -->
    <el-dialog v-model="createBackupDialogVisible" title="创建数据库备份" width="500px">
      <el-form :model="backupForm" :rules="backupRules" ref="backupFormRef" label-width="100px">
        <el-form-item label="数据库连接" prop="connection_id">
          <el-select v-model="backupForm.connection_id" placeholder="请选择数据库连接">
            <el-option
              v-for="conn in connectionList"
              :key="conn.id"
              :label="conn.name"
              :value="conn.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备份名称" prop="backup_name">
          <el-input v-model="backupForm.backup_name" placeholder="请输入备份名称" />
        </el-form-item>
        <el-form-item label="备份类型" prop="backup_type">
          <el-select v-model="backupForm.backup_type" placeholder="请选择备份类型">
            <el-option label="完整备份" value="full" />
            <el-option label="增量备份" value="incremental" />
            <el-option label="差异备份" value="differential" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createBackupDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createBackup" :loading="creating">创建备份</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 恢复备份对话框 -->
    <el-dialog v-model="restoreDialogVisible" title="恢复数据库备份" width="500px">
      <el-form :model="restoreForm" label-width="120px">
        <el-form-item label="备份文件">
          <el-input v-model="currentBackup.name" disabled />
        </el-form-item>
        <el-form-item label="目标数据库连接">
          <el-select v-model="restoreForm.target_connection_id" placeholder="请选择目标数据库连接">
            <el-option
              v-for="conn in connectionList"
              :key="conn.id"
              :label="conn.name"
              :value="conn.id"
            />
          </el-select>
          <div class="form-tip">留空则恢复到原数据库</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="restoreDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmRestore" :loading="restoring">确认恢复</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const restoring = ref(false)
const createBackupDialogVisible = ref(false)
const restoreDialogVisible = ref(false)
const backupFormRef = ref()

const searchForm = reactive({
  connection_id: '',
  status: ''
})

const backupForm = reactive({
  connection_id: '',
  backup_name: '',
  backup_type: 'full'
})

const restoreForm = reactive({
  target_connection_id: ''
})

const backupRules = {
  connection_id: [{ required: true, message: '请选择数据库连接', trigger: 'change' }],
  backup_name: [{ required: true, message: '请输入备份名称', trigger: 'blur' }],
  backup_type: [{ required: true, message: '请选择备份类型', trigger: 'change' }]
}

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const backupList = ref([])
const connectionList = ref([])
const currentBackup = ref({})

// 方法
const fetchBackupList = async () => {
  loading.value = true
  try {
    const response = await api.get('/database/backups/', {
      params: {
        page: pagination.page,
        page_size: pagination.pageSize,
        ...searchForm
      }
    })
    
    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        backupList.value = data
        pagination.total = data.length
      } else if (data && Array.isArray(data.results)) {
        backupList.value = data.results
        pagination.total = data.total || data.results.length
      } else {
        backupList.value = []
        pagination.total = 0
      }
    }
  } catch (error) {
    console.error('获取备份列表失败:', error)
    ElMessage.error('获取备份列表失败')
  } finally {
    loading.value = false
  }
}

const fetchConnectionList = async () => {
  try {
    const response = await api.get('/database/connections/')
    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        connectionList.value = data.filter((conn: any) => conn.is_active)
      } else if (data && Array.isArray(data.results)) {
        connectionList.value = data.results.filter((conn: any) => conn.is_active)
      }
    }
  } catch (error) {
    console.error('获取连接列表失败:', error)
  }
}

const resetSearch = () => {
  searchForm.connection_id = ''
  searchForm.status = ''
  pagination.page = 1
  fetchBackupList()
}

const showCreateBackupDialog = () => {
  backupForm.connection_id = ''
  backupForm.backup_name = ''
  backupForm.backup_type = 'full'
  createBackupDialogVisible.value = true
}

const createBackup = async () => {
  if (!backupFormRef.value) return
  
  await backupFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    creating.value = true
    try {
      const response = await api.post('/database/backups/create_backup/', backupForm)
      
      if (response.data.success) {
        ElMessage.success('备份创建成功')
        createBackupDialogVisible.value = false
        fetchBackupList()
      }
    } catch (error) {
      console.error('创建备份失败:', error)
      ElMessage.error('创建备份失败')
    } finally {
      creating.value = false
    }
  })
}

const restoreBackup = (backup: any) => {
  currentBackup.value = backup
  restoreForm.target_connection_id = ''
  restoreDialogVisible.value = true
}

const confirmRestore = async () => {
  try {
    await ElMessageBox.confirm(
      '恢复备份将覆盖目标数据库的现有数据，此操作不可逆。确定要继续吗？',
      '确认恢复',
      {
        confirmButtonText: '确定恢复',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    restoring.value = true
    const response = await api.post(`/database/backups/${currentBackup.value.id}/restore_backup/`, {
      target_connection_id: restoreForm.target_connection_id || null
    })
    
    if (response.data.success) {
      ElMessage.success('数据库恢复成功')
      restoreDialogVisible.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复备份失败:', error)
      ElMessage.error('恢复备份失败')
    }
  } finally {
    restoring.value = false
  }
}

const deleteBackup = async (backup: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个备份吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.delete(`/database/backups/${backup.id}/delete_backup/`)
    if (response.data.success) {
      ElMessage.success('备份删除成功')
      fetchBackupList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除备份失败:', error)
      ElMessage.error('删除备份失败')
    }
  }
}

const downloadBackup = (backup: any) => {
  ElMessage.info('下载功能开发中...')
}

const getBackupTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    'full': 'primary',
    'incremental': 'success',
    'differential': 'warning'
  }
  return colors[type] || 'info'
}

const getBackupTypeText = (type: string) => {
  const texts: Record<string, string> = {
    'full': '完整备份',
    'incremental': '增量备份',
    'differential': '差异备份'
  }
  return texts[type] || type
}

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    'completed': 'success',
    'running': 'warning',
    'failed': 'danger'
  }
  return colors[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'completed': '已完成',
    'running': '备份中',
    'failed': '失败'
  }
  return texts[status] || status
}

// 生命周期
onMounted(() => {
  fetchConnectionList()
  fetchBackupList()
})
</script>

<style scoped>
.backup-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
